package com.colorful.insuranceproject.mine;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.colorful.insuranceproject.R;
import com.colorful.insuranceproject.apush.APushProcessor;
import com.colorful.insuranceproject.base.TitleActivity;
import com.colorful.insuranceproject.bean.MessageContentBean;
import com.colorful.insuranceproject.bean.PushMessage;
import com.colorful.insuranceproject.bean.QRCodeBean;
import com.colorful.insuranceproject.consts.CodeTable;
import com.colorful.insuranceproject.request.MicroDrugRequest;
import com.github.yoojia.zxing.qrcode.Encoder;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.lovely3x.common.managements.user.UserManager;
import com.lovely3x.common.utils.Response;
import com.lovely3x.common.utils.ViewUtils;
import com.lovely3x.jsonparser.model.JSONObject;
import com.lovely3x.loginandresgiter.bean.SimpleUser;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by handsome-Bob on 2017/9/13.
 * <p>
 * 药店付款
 */
public class PaymentCodeActivity extends TitleActivity implements APushProcessor.MsgPassThrough {

    private static final int GET_PAYMENT_CODE_VALUE = 0X1;

    private static final int CLICKED_BUTTOM_URL = 0X2;

    private MicroDrugRequest microDrugRequest;

    @Bind(R.id.tv_exchange)
    TextView tvBtn;

    @Bind(R.id.tv_money)
    TextView tvMoney;

    @Bind(R.id.view_qr)
    ImageView qr;

    @Bind(R.id.view_long_qr)
    ImageView longQr;

    @Bind(R.id.tv_show_number)
    TextView tvShowNumber;

    private CountDownTimer mDownTimer;

    MessageContentBean bean;

    SimpleUser simpleUser = (SimpleUser) UserManager.getInstance().getCurrentUser();

    @Override
    protected int getContentView() {
        return R.layout.activity_payment_code;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        setTitle(getString(R.string.drug_pay));
        getViewDivider().setVisibility(View.GONE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        APushProcessor.getInstance().registerCallBack(this);
    }

    @Override
    protected void onViewInitialized() {
        microDrugRequest = new MicroDrugRequest(getHandler());
        setQrCode("0123456789");

        /*
         *   倒计时180秒
         */
        mDownTimer = new CountDownTimer(600 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                //Ignore
            }

            @Override
            public void onFinish() {
                microDrugRequest.getQrCode(GET_PAYMENT_CODE_VALUE);
            }
        };

        microDrugRequest.getQrCode(GET_PAYMENT_CODE_VALUE);
    }

    /**
     * 创建条形码的方法
     */
    public Bitmap createOneQRCode(String content) throws Exception {
        int heights = ViewUtils.dp2pxF(80);
        int widths = ViewUtils.dp2pxF(300);
        BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.CODE_128, widths, heights);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = 0xff000000;
                }
            }
        }
        Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bm.setPixels(pixels, 0, width, 0, 0, width, height);
        return bm;
    }

    @Override
    protected void handleResponseMessage(Message msg, Response response) {
        super.handleResponseMessage(msg, response);
        switch (msg.what) {
            case GET_PAYMENT_CODE_VALUE:
                if (response.isSuccessful) {
                    setQrCode(((QRCodeBean) response.obj).getQrCode());
                    tvMoney.setText(getString(R.string.cka_money, ((QRCodeBean) response.obj).getAmount()));
                    mDownTimer.start();
                } else {
                    showToast(CodeTable.getInstance().getCodeDescription(response));
                }
                break;

            // 点击页面监听按钮
            case CLICKED_BUTTOM_URL:
                if (response.isSuccessful) {
                    launchActivity(PaySuccessActivity.class, PaySuccessActivity.EXTRA_BEAN, bean);
                } else {
                    bean.setType(2);
                    launchActivity(PaySuccessActivity.class, PaySuccessActivity.EXTRA_BEAN, bean);
                }
                break;
        }
    }

    private void setQrCode(String obj) {
        String textNumber = "";
        for (int i = 0; i < obj.length(); i++) {
            char item = obj.charAt(i);
            textNumber += item + " ";
        }
        tvShowNumber.setText(textNumber);

        /*
         *  生成的条形码图片
         */
        Bitmap image = null;
        try {
            //当用户输入的url不为空时
            if (!"".equals(obj)) {
                image = createOneQRCode(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (image != null) {
            longQr.setImageBitmap(image);
        }

        /*
         *   这里我需要加载一个二维码
         */
        int dimension = ViewUtils.dp2pxF(200);
        dimension = Math.min(ViewUtils.getWidth(), dimension);

        final Encoder encoder = new Encoder.Builder()
                .setBackgroundColor(0xFFFFFFFF) // 指定背景颜色，默认为白色
                .setCodeColor(0xFF000000) // 指定编码块颜色，默认为黑色
                .setOutputBitmapWidth(dimension) // 生成图片宽度
                .setOutputBitmapHeight(dimension) // 生成图片高度
                .setOutputBitmapPadding(0) // 设置为没有白边
                .build();
        Bitmap mQrCodeImage = encoder.encode(obj);
        qr.setImageBitmap(mQrCodeImage);
    }

    @Override
    public void restoreInstanceOnCreateBefore(@NonNull Bundle savedInstance) {

    }

    @Override
    public void restoreInstanceOnCreateAfter(@NonNull Bundle savedInstance) {

    }

    @Override
    protected void onBackClicked(View v) {
        super.onBackClicked(v);
        mDownTimer.cancel();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mDownTimer.cancel();
    }

    //  ------------------------ 透传处理  -----------------------------------
    @Override
    public boolean onCommonMsg(PushMessage pushMessage) {
        return false;
    }

    @Override
    public boolean onPayStatus(final PushMessage pushMessage) {
        bean = convertMsg(pushMessage.getContent());
        final String message = bean.isEnough() ? getString(R.string.pay_money_show, bean.getKeKangAnPay()) : getString(R.string.pay_money_show_more, bean.getKeKangAnPay(), bean.getOtherPay());
        new AlertDialog.Builder(mActivity)
                .setTitle(pushMessage.getTitle())
                .setMessage(message)
                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        bean.setType(1);
                        microDrugRequest.aboutQrPageConst("confirm", simpleUser.getUid(), pushMessage.getContent(), CLICKED_BUTTOM_URL);
                    }
                }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                bean.setType(0);
                microDrugRequest.aboutQrPageConst("cancel", simpleUser.getUid(), pushMessage.getContent(), CLICKED_BUTTOM_URL);
            }
        }).show();
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        APushProcessor.getInstance().unregisterCallBack(this);
    }

    /**
     * 转换消息为实体并存储该消息
     *
     * @param extra 需要转换存储的消息内容
     */
    protected MessageContentBean convertMsg(String extra) {
        JSONObject jo = new JSONObject(extra);
        return jo.createObject(MessageContentBean.class);
    }
}
